let header = document.querySelector("header");
let mainBox = document.querySelector(".mainBox");
let articalBox = mainBox.querySelector(".articalBox");
let sidebar = mainBox.querySelector(".sidebar");
let footer = document.querySelector("footer");
let diaryItems, diaryObj = {} , maxTime , minTime;
let nowShowingDiv , allYearArr = [] , pageTime = {};

function toHomepage(e) { // 跳转到首页
    location.href = "../../html/ys/index.html";
}

(() => { // 头部
    let left = header.querySelector(".left");
    let leftDivs = left.querySelectorAll("div");
    leftDivs[0].addEventListener("click", toHomepage);
    leftDivs[1].addEventListener("click", toHomepage);

})();

function changeDate(time) { // 改变侧边栏显示头部的日期
    let date = sidebar.querySelector(".date");
    let timeObj = new Date(time);
    let month = date.querySelector(".month");
    let year = date.querySelector(".year");
    let day = date.querySelector(".day");
    month.textContent = `${pad(timeObj.getMonth() + 1)}/${pad(timeObj.getDate())}`;
    year.textContent = `/${timeObj.getFullYear()}`;
    let arr = ["日" , "一" , "二" , "三" , "四" , "五" , "六"];
    day.textContent = `星期${arr[timeObj.getDay()]}`;
    pageTime.year = timeObj.getFullYear();
    pageTime.month = timeObj.getMonth() + 1;
    pageTime.date = timeObj.getDate();
}

function pad(num){
    return num.toString().padStart(2 , 0);
}

(async () => {
    let res = await axios({
        url: "/api/diaryItem",
        params: {
            diarybookId: "632595e0e24deb53641c4b2b"  // localStorage.getItem("diarybookId")
        }
    });
    if (res.data.code) {
        console.log(res.data.msg);
        return;
    }
    diaryItems = res.data.data;
    diaryItems.sort((a, b) => { // 排序
        return Date.parse(a.createAt) - Date.parse(b.createAt);
    })

    res = await axios({
        url : "/api/diarybook/content",
        params : {
            diarybookId: "632595e0e24deb53641c4b2b"
        }
    })
    if (res.data.code) {
        console.log(res.data.msg);
        return;
    }
    let yearSelect = sidebar.querySelector("#yearSelect");
    let monthSelect = sidebar.querySelector("#monthSelect");
    let titleBox = articalBox.querySelector("h2");
    titleBox.textContent = `《${res.data.data.diarybook.title}》已过期`;

    if(diaryItems.length === 0){
        let timeObj = new Date(); 
        monthSelect = sidebar.querySelector("#monthSelect");
        yearSelect.value = timeObj.getFullYear();
        monthSelect.value = timeObj.getMonth() + 1;
        updatedDateUl(timeObj);
        return;
    }
    for (let i = 0; i < diaryItems.length; i++) {
        let timeObj = new Date(diaryItems[i].createAt);
        let yearObj = diaryObj[timeObj.getFullYear()];
        let monthObj = yearObj?.[timeObj.getMonth()];
        let dayObj = monthObj?.[timeObj.getDate()];
        let hours = timeObj.getHours();
        if (!yearObj) yearObj = diaryObj[timeObj.getFullYear()] = {};
        if (!monthObj) monthObj = yearObj[timeObj.getMonth() + 1] = {};
        if (!dayObj) dayObj = monthObj[timeObj.getDate()] = [];
        dayObj.push({
            index: i,
            time: `${pad(hours)}:${pad(timeObj.getMinutes())} ${hours >= 12 ? "pm" : "am"}`,
            content : diaryItems[i].content,
            reply : diaryItems[i].replyId,
            img : diaryItems[i].imgUrl
        });
    }
    maxTime = Date.parse(diaryItems[diaryItems.length - 1].createAt);
    minTime = Date.parse(diaryItems[0].createAt);

    // 给年份的下拉框赋值
    yearSelect.innerHTML = "";
    let fragment = document.createDocumentFragment();
    for (let key in diaryObj) {
        let option = document.createElement("option");
        option.value = key;
        option.textContent = key;
        fragment.append(option);
    }
    yearSelect.append(fragment);

    // diaryItems[0].createAt 2022-9-1
    updatedDateUl(new Date(minTime)); // 初始化日历表格
    changeDate(new Date(minTime));
    // 初始化select框的值
    let timeObj = new Date(minTime);
    yearSelect.value = timeObj.getFullYear();
    monthSelect.value = timeObj.getMonth() + 1;
    monthSelect.addEventListener("change", selectChange);
    yearSelect.addEventListener("change", selectChange);
    selectChange();

    // 时间前进和后退显示和绑定事件
    let backBtn = articalBox.querySelector(".backBtn");
    let frontBtn = articalBox.querySelector(".frontBtn");
    let lastMonth = sidebar.querySelector(".lastMonth");
    let nextMonth = sidebar.querySelector(".nextMonth");
    showBtn();
    nextMonth.addEventListener("click" , nextMonthClick);
    lastMonth.addEventListener("click" , lastMonthClick);
})();

function showBtn(){
    let backBtn = articalBox.querySelector(".backBtn");
    let frontBtn = articalBox.querySelector(".frontBtn");
    let lastMonth = sidebar.querySelector(".lastMonth");
    let nextMonth = sidebar.querySelector(".nextMonth");
    let timeObj = new Date(`${pageTime.year}-${pageTime.month}-${pageTime.date}`);
    let maxTimeObj = new Date(maxTime);
    let minTimeObj = new Date(minTime);
    if (Date.parse(timeObj) <= minTime) {
        backBtn.style.display = "none";
        frontBtn.style.display = "block";
    } else if (Date.parse(timeObj) >= maxTime){
        backBtn.style.display = "block";
        frontBtn.style.display = "none";
    } else {
        frontBtn.style.display = "block";
        backBtn.style.display = "block";
    }
    if (+maxTimeObj.getFullYear() < +pageTime.year){
        lastMonth.style.display = "block";
        nextMonth.style.display = "none";
    } else if (+minTimeObj.getFullYear() > +pageTime.year) {
        lastMonth.style.display = "none";
        nextMonth.style.display = "block";
    } else if (+maxTimeObj.getFullYear() == +pageTime.year){
        if (+maxTimeObj.getMonth() + 1 <= +pageTime.month) {
            lastMonth.style.display = "block";
            nextMonth.style.display = "none";
        } else {

        }
    } else if (+minTimeObj.getFullYear() == +pageTime.year){
        
    }
}

function lastMonthClick(e){

}

function nextMonthClick(e){
    let yearSelect = sidebar.querySelector("#yearSelect");
    let monthSelect = sidebar.querySelector("#monthSelect");
    let month = monthSelect.value;
    let year = yearSelect.value;
    let obj = diaryObj?.[year]?.[month];
    if(obj){
        for(let key in diaryObj[year]){
            if(Number(key) > Number(month)){
                monthSelect.value = key;
                selectChange();
            }
        }
    } else {

    }
}

function backBtnClick(e){

}

function frontBtnClick(e){
    let yearSelect = sidebar.querySelector("#yearSelect");
    let monthSelect = sidebar.querySelector("#monthSelect");
    let month = monthSelect.value;
    let year = yearSelect.value;
    let obj = diaryObj?.[year]?.[month];
    if(obj){
        let nowday = nowShowingDiv.textContent;
        for(let key in obj){
            if (Number(key) > Number(nowday)){
                diaryObj[year][month][key].dataDivEl.click();
                let timeObj = new Date(`${year}-${month}-${key}`);
                let frontBtn = articalBox.querySelector(".frontBtn");
                if(timeObj >= maxTime){
                    frontBtn.style.display = "none"; 
                } else {
                    frontBtn.style.display = "block";
                }
                return;
            }
        }
        for(let key in diaryObj[year]){
            if (Number(key) > Number(month)){
                monthSelect.value = key;
                selectChange();
                let maxTimeObj = new Date(timeObj);
                return;
            }
        }
    } else {
        let yearArr = [];
        for(let key in diaryObj){
            yearArr.push(Number(key));
            // if()
        }
    }
}

function selectChange(e){
    let month = sidebar.querySelector("#monthSelect").value;
    let year = sidebar.querySelector("#yearSelect").value;
    let noDiaryItem = articalBox.querySelector(".noDiaryItem");
    updatedDateUl(new Date(`${year}-${month}`));
    let obj = diaryObj?.[year]?.[month];
    if(obj){
        // 转到该月第一天并显示articalBox
        let arr = [];
        for(let key in obj){
            arr.push(key);
        }
        diaryObj[year][month][arr[0]].dataDivEl.click();
    } else {
        noDiaryItem.style.display = "block";
        changeArticalBox();
        changeDate(new Date(`${year}-${month}`));
    }
}

function changeArticalBox(diarys){
    let oneDayDiaries = articalBox.querySelector(".oneDayDiaries");
    let noDiaryItem = articalBox.querySelector(".noDiaryItem");
    if (diarys?.length){
        let fragment = document.createDocumentFragment();
        for (let item of diarys){
            let div = document.createElement("div");
            div.innerHTML = `
                <div class="time">${item.time}</div>
                ${item.img ? `<img src="http://localhost:8000${item.img}" alt="">` : ""}
                <p>${item.content}</p>
                <div class="bottom"><span>${item.reply.length ? item.reply.length : ''}</span>回复</div>
            `
            fragment.append(div);
        }
        oneDayDiaries.innerHTML = '';
        oneDayDiaries.append(fragment);
        noDiaryItem.style.display = "none";
        oneDayDiaries.style.display = "block";
    } else {
        noDiaryItem.style.display = "block";
        oneDayDiaries.style.display = "none";
    }
}

function calendarItemClick(e){ // 可以点击的日历的点击事件
    let target = e.target;
    nowShowingDiv?.classList.remove("today");
    nowShowingDiv = target;
    nowShowingDiv.classList.add("today");
    changeArticalBox(target.dataDiaryItemArr);
    changeDate(new Date(target.dataDate));
}

function updatedDateUl(timeObj) {  // 修改日历表格
    let dateUl = sidebar.querySelector('.dayItemBox .changeBox');
    let fragment = document.createDocumentFragment();
    let month = timeObj.getMonth();
    let year = timeObj.getFullYear();
    timeObj.setMonth(month + 1);
    timeObj.setDate(0);
    for (let i = timeObj.getDate(); i > 0; i--) {
        let newLi = document.createElement('div');
        newLi.textContent = `${i}`;
        if (diaryObj?.[year]?.[month + 1]?.[i]?.length) {
            newLi.classList.add("hasDiary");
            newLi.dataDiaryItemArr = diaryObj[year][month + 1][i];
            newLi.dataIndex = diaryObj[year][month + 1][i].index;
            newLi.addEventListener("click" , calendarItemClick);
            newLi.dataDate = `${year}-${month + 1}-${i}`
            diaryObj[year][month + 1][i].dataDivEl = newLi;
        }
        fragment.prepend(newLi);
    }
    timeObj.setMonth(month, 0);
    for (let i = timeObj.getDay(); i > 0; i--) {
        let newLi = document.createElement('div');
        fragment.prepend(newLi);
    }
    timeObj.setMonth(month + 1, 0);
    for (let i = timeObj.getDay(); i <= 6; i++) {
        let div = document.createElement("div");
        fragment.append(div);
    }
    dateUl.innerHTML = '';
    dateUl.append(fragment);
}